package com.GB26875_3_2011.config;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 蒋仕国
 * @projectName GB26875_3_211
 * @ClassName ChannelManager
 * @date 2025-01-13 10:55
 * @Description: TODO []
 */
@Slf4j
public final class ChannelManager {

    private static final ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private static final Map<String, ChannelId> channelIdMap = new ConcurrentHashMap<>();


    public static void add(String sourceAddress, Channel channel) {
        boolean added = channelGroup.add(channel);
        if (added) {
            channelIdMap.put(sourceAddress, channel.id());
        }
    }

    public static Channel get(String sourceAddress) {
        ChannelId channelId = channelIdMap.get(sourceAddress);
        if (channelId == null) {
            return null;
        }
        Channel channel = channelGroup.find(channelId);
        if (channel == null) {
            channelIdMap.remove(sourceAddress);
        }
        return channel;
    }


    public static void remove(Channel channel) {
        channelGroup.remove(channel);
    }

}
